package net.chowda.castcluster.action;

import net.chowda.castcluster.util.LogUtil;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * this is a hacky landing point for bookmarklet requests...
 *
 * the url is "parsed" to determine the action to take.
 *
 * if it's a special domain like youtube or google video we attempt to figure out if it's video/user/fav/whatev...
 *
 * if it's RSS and there's more than one we need more feedback from the user.
 */
public class LinkAction extends PlayListAction {
    private static final Logger LOG = LogUtil.getLogger(LinkAction.class);

    private String url;
    private String selectedPlayList;
    private String selectedText;
    private String title;


    // when videoUrl is set the link decider will make a request to populate the video preview.
    private String videoUrl;

    // videoUrl = foundProvider + "|" + foundItemType + "|" + foundItem;
    private String foundProvider = "unknown";
    private String foundItemType = "unknown";
    private String foundItem     = "unknown";

    private PlayListAction playListAction;

    // <link> tags from the source page... RSS feeds.
    private List<String> linkTitles = new ArrayList<String>();
    private List<String> linkUrls = new ArrayList<String>();

    @DefaultHandler
    public Resolution checkLink() {
        String domain = getFirstMatchingGroup("http[s]?://(.+)/.*", url);
        if(domain != null) {
            // TODO... this is clearly not scalable... hacked it in here to test it out... now it's PITA legacy code...
            if(domain.contains("video.google.")) {
                //http://video.google.com/videoplay?docid=656193898147576910
                String video = getFirstMatchingGroup("videoplay.*?docid=([^&]+)", url);
                if (video != null && video.trim().length() > 0) {
                    foundProvider = "gv";
                    foundItemType = "video";
                    foundItem = video;
                } else {
                    if(linkUrls.size() > 0) {
                        foundProvider = "rss";
                    }
                }
                videoUrl = foundProvider + "|" + foundItemType + "|" + foundItem;
            } else if(domain.contains("revver.com")) {
                foundProvider = "rv";
                foundItem = getFirstMatchingGroup("watch/([^\\?^/^&]+)", url);
                if(foundItem != null) {
                    foundItemType = "video";
                } else {
                    foundItem = getFirstMatchingGroup("account/show/([^\\?^/^&]+)", url);
                    foundItemType = "user";
                }
                videoUrl = foundProvider + "|" + foundItemType + "|" + foundItem;
            } else if(domain.contains("youtube.com")) {
                foundProvider = "yt";
                // user pages usually look like this: http://www.youtube.com/profile?user=username
                String user     = getFirstMatchingGroup("profile\\?.*?user=([^&]+)", url);
                // favorites usually look like this: http://www.youtube.com/profile_favorites?user=username
                String userFavs = getFirstMatchingGroup("profile_favorites.*?user=([^&]+)", url);
                // videos look like this: http://www.youtube.com/watch?v=VIDEOID
                String video    = getFirstMatchingGroup("watch.*?v=([^&]+)", url);
                if(user == null) {
                    // sometimes the user url looks like this: http://www.youtube.com/user/username
                    user = getFirstMatchingGroup("\\/user\\/([^&^\\/]+)", url);
                }

                // set the url bits according to what we parsed out.
                if(user != null) {
                    foundItemType = "user";
                    foundItem = user;
                } else if(userFavs != null) {
                    foundItemType = "favs";
                    foundItem = userFavs;
                } else if(video != null) {
                    foundItemType = "video";
                    foundItem = video;
                }
                videoUrl = foundProvider + "|" + foundItemType + "|" + foundItem;
            } else {
                // if there are some <link> tags in the page.. we'll just set the provider type...
                // the UI will show them to the user for decision time.
                if(linkUrls.size() > 0) {
                    foundProvider = "rss";
                }
            }
        } else if(url.startsWith("file:")) {
                foundProvider = "dir";
                foundItemType = "all";
                foundItem = url.substring(7);
            videoUrl = foundProvider + "|" + foundItemType + "|" + foundItem;
        }

        // populate the playlists
        playListAction = new PlayListAction();
        playListAction.setContext(getContext());
        try {
            playListAction.doLists();
        } catch (Exception e) {
            LOG.error("problem fetching playlists!", e);
        }
        return new ForwardResolution("/view/link_decider.jsp");
    }

    private static String getFirstMatchingGroup(String regex, String string) {
        String myMatch = null;
        if (string != null && regex != null) {
            Matcher matcher = Pattern.compile(regex).matcher(string);
            if(matcher.find() && matcher.groupCount() >= 1) {
                myMatch = matcher.group(1);
            }
        }
        return myMatch;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public PlayListAction getPlayListAction() {
        return playListAction;
    }

    public void setPlayListAction(PlayListAction playListAction) {
        this.playListAction = playListAction;
    }

    public String getFoundProvider() {
        return foundProvider;
    }

    public void setFoundProvider(String foundProvider) {
        this.foundProvider = foundProvider;
    }

    public String getFoundItemType() {
        return foundItemType;
    }

    public void setFoundItemType(String foundItemType) {
        this.foundItemType = foundItemType;
    }

    public String getFoundItem() {
        return foundItem;
    }

    public void setFoundItem(String foundItem) {
        this.foundItem = foundItem;
    }

    public String getSelectedPlayList() {
        return selectedPlayList;
    }

    public void setSelectedPlayList(String selectedPlayList) {
        this.selectedPlayList = selectedPlayList;
    }

    public String getSelectedText() {
        return selectedText;
    }

    public void setSelectedText(String selectedText) {
        this.selectedText = selectedText;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getVideoUrl() {
        return videoUrl;
    }

    public void setVideoUrl(String videoUrl) {
        this.videoUrl = videoUrl;
    }

    public List<String> getLinkTitles() {
        return linkTitles;
    }

    public void setLinkTitles(List<String> linkTitles) {
        this.linkTitles = linkTitles;
    }

    public List<String> getLinkUrls() {
        return linkUrls;
    }

    public void setLinkUrls(List<String> linkUrls) {
        this.linkUrls = linkUrls;
    }
}
